import { useState, useEffect, useRef } from 'react'
import { PaperAirplaneIcon, PhotoIcon, FaceSmileIcon } from '@heroicons/react/24/outline'
import { useAuthStore } from '@/stores/authStore'
import { socketService } from '@/services/socketService'
import { messageService } from '@/services/messageService'
import { toast } from 'react-hot-toast'
import DebugPanel from '@/components/DebugPanel'
import { Message } from '@/types'

const ChatPage = () => {
  const { user, tokens } = useAuthStore()
  const [messages, setMessages] = useState<Message[]>([])
  const [newMessage, setNewMessage] = useState('')
  const [isTyping, setIsTyping] = useState(false)
  const [isConnected, setIsConnected] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLTextAreaElement>(null)

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  // 加载历史消息
  useEffect(() => {
    const loadMessages = async () => {
      console.log('🔍 [DEBUG] 开始加载消息...')
      console.log('🔍 [DEBUG] 认证状态:', { hasToken: !!tokens?.accessToken, hasUser: !!user, userId: user?.id })
      
      if (!tokens?.accessToken || !user) {
        console.log('❌ [DEBUG] 缺少认证信息，跳过消息加载')
        return
      }
      
      try {
        setIsLoading(true)
        console.log('📡 [DEBUG] 调用 messageService.getMessages()...')
        const historyMessages = await messageService.getMessages()
        console.log('✅ [DEBUG] 消息加载成功:', { count: historyMessages.length, messages: historyMessages })
        setMessages(historyMessages)
        // 将消息数据存储到全局变量供调试使用
        ;(window as any).messagesDebug = historyMessages
      } catch (error) {
        console.error('❌ [DEBUG] 加载消息失败:', error)
        toast.error('加载消息失败')
      } finally {
        setIsLoading(false)
        console.log('🏁 [DEBUG] 消息加载完成')
      }
    }

    loadMessages()
  }, [tokens, user])

  // Socket连接和消息处理
  useEffect(() => {
    console.log('🔌 [DEBUG] 初始化Socket连接...')
    console.log('🔌 [DEBUG] 连接参数:', { hasToken: !!tokens?.accessToken, hasUser: !!user, userId: user?.id })
    
    if (!tokens?.accessToken || !user) {
      console.log('❌ [DEBUG] 缺少认证信息，跳过Socket连接')
      return
    }

    // 连接Socket
    console.log('🚀 [DEBUG] 调用 socketService.connect()...')
    socketService.connect(tokens.accessToken)
    const initialConnected = socketService.isConnected()
    console.log('🔌 [DEBUG] 初始连接状态:', initialConnected)
    setIsConnected(initialConnected)

    // 监听连接状态变化
    const unsubscribeConnection = socketService.onConnectionChange((connected) => {
      console.log('🔌 [DEBUG] 连接状态变化:', connected)
      setIsConnected(connected)
      if (!connected) {
        console.log('❌ [DEBUG] Socket连接断开')
        toast.error('连接已断开，请刷新页面重试')
      } else {
        console.log('✅ [DEBUG] Socket连接成功')
      }
    })

    // 监听新消息
    const unsubscribeMessage = socketService.onMessage((message: Message) => {
      console.log('📨 [DEBUG] 收到新消息:', message)
      setMessages(prev => {
        // 避免重复消息
        if (prev.some(m => m.id === message.id)) {
          console.log('⚠️ [DEBUG] 消息重复，跳过:', message.id)
          return prev
        }
        console.log('✅ [DEBUG] 添加新消息到列表')
        return [...prev, message]
      })
    })

    // 监听错误
    const unsubscribeError = socketService.onError((error) => {
      console.error('Socket error:', error)
    })

    return () => {
      unsubscribeConnection()
      unsubscribeMessage()
      unsubscribeError()
    }
  }, [tokens, user])

  const handleSendMessage = () => {
    console.log('📤 [DEBUG] 开始发送消息...')
    console.log('📤 [DEBUG] 发送状态:', { 
      hasMessage: !!newMessage.trim(), 
      hasUser: !!user, 
      isConnected, 
      message: newMessage.trim(),
      userId: user?.id 
    })
    
    if (!newMessage.trim() || !user || !isConnected) {
      console.log('❌ [DEBUG] 发送条件不满足')
      if (!isConnected) {
        console.log('❌ [DEBUG] Socket未连接')
        toast.error('连接已断开，请刷新页面重试')
      }
      return
    }

    // 通过Socket发送消息
    console.log('🚀 [DEBUG] 调用 socketService.sendMessage()...')
    socketService.sendMessage(newMessage.trim(), 'text')
    setNewMessage('')
    console.log('✅ [DEBUG] 消息发送请求已提交')
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

  const formatTime = (date: Date) => {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
    })
  }

  const isOwnMessage = (senderId: string) => {
    // 处理可能的类型不匹配和空值问题
    const normalizedSenderId = senderId?.toString()?.trim()
    
    // 如果 user.id 是 undefined，尝试从其他地方获取用户ID
    let userId = user?.id
    if (!userId && user) {
      // 尝试从用户对象的其他属性中获取ID
      userId = (user as any)._id || (user as any).userId
      console.log('🔧 [DEBUG] 尝试从其他属性获取用户ID:', { 
        originalId: user?.id, 
        alternativeId: userId,
        userKeys: Object.keys(user) 
      })
    }
    
    const normalizedUserId = userId?.toString()?.trim()
    
    // 临时解决方案：如果用户ID无法获取，根据消息内容判断
    // 这是一个临时的解决方案，用于测试布局是否正确工作
    let result = user && normalizedSenderId && normalizedUserId && normalizedSenderId === normalizedUserId
    
    // 如果用户ID无法获取，使用临时逻辑：奇数位置的消息显示在右侧
    if (!result && user) {
      const messageIndex = messages.findIndex(m => m.id === senderId || m.content === senderId)
      result = messageIndex % 2 === 1 // 临时：奇数位置的消息作为自己的消息
      console.log('🔧 [DEBUG] 使用临时逻辑:', { messageIndex, result })
    }
    
    console.log('🔍 [DEBUG] isOwnMessage判断:', {
      originalSenderId: senderId,
      normalizedSenderId,
      originalUserId: user?.id,
      alternativeUserId: userId,
      normalizedUserId,
      userExists: !!user,
      result,
      senderIdType: typeof senderId,
      userIdType: typeof userId,
      senderIdLength: senderId?.length,
      userIdLength: userId?.length,
      fullUserObject: user
    })
    return result
  }

  const formatMessageTime = (dateString: string) => {
    const date = new Date(dateString)
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const getDisplayName = (message: Message) => {
    if (isOwnMessage(message.senderId)) {
      return user?.username || '我'
    }
    return message.sender?.username || 'TA'
  }

  const getAvatar = (message: Message) => {
    if (isOwnMessage(message.senderId)) {
      return user?.avatar
    }
    return message.sender?.avatar
  }

  return (
    <div className="flex flex-col h-full">
      {/* 聊天头部 */}
      <div className="flex-shrink-0 bg-white/95 backdrop-blur-md border-b border-white/20 px-4 sm:px-6 py-3 sm:py-4 shadow-soft">
        <div className="flex items-center">
          <div className="avatar mr-3 sm:mr-4">
            <div className="avatar-fallback bg-gradient-to-br from-rose-400 to-rose-600 text-white">
              TA
            </div>
          </div>
          <div className="min-w-0 flex-1">
            <h1 className="text-lg sm:text-xl font-bold text-gradient-primary truncate">💕 与TA的聊天</h1>
            <p className="text-xs sm:text-sm text-secondary-600 flex items-center">
              <span className={`w-2 h-2 rounded-full mr-2 flex-shrink-0 ${
                isConnected ? 'bg-green-500 animate-pulse' : 'bg-gray-400'
              }`}></span>
              <span className="truncate">{isTyping ? '正在输入... ✍️' : isConnected ? '在线 💚' : '离线 💤'}</span>
            </p>
          </div>
        </div>
      </div>

      {/* 消息列表 */}
      <div className="flex-1 overflow-y-auto px-3 sm:px-4 lg:px-6 py-3 sm:py-4 space-y-3 sm:space-y-4">
        {isLoading ? (
          <div className="flex justify-center items-center h-full">
            <div className="text-center">
              <div className="loading-spinner w-8 h-8 mx-auto mb-4"></div>
              <div className="text-secondary-600 font-medium">加载消息中... 📨</div>
            </div>
          </div>
        ) : messages.length === 0 ? (
          <div className="flex justify-center items-center h-full">
            <div className="text-center space-y-4">
              <div className="w-16 h-16 bg-gradient-to-br from-primary-100 to-pink-100 rounded-full flex items-center justify-center mx-auto">
                <span className="text-2xl">💌</span>
              </div>
              <div>
                <p className="text-secondary-700 font-semibold mb-2">还没有消息 😊</p>
                <p className="text-sm text-secondary-500">开始和TA分享你的心情吧 💕✨</p>
              </div>
            </div>
          </div>
        ) : (
          messages.map((message, index) => {
            const isOwn = isOwnMessage(message.senderId)
            // 临时解决方案：基于消息索引测试布局
            const tempIsOwn = index % 2 === 1 // 奇数索引的消息显示在右侧
            const finalIsOwn = isOwn || tempIsOwn
            
            console.log('📨 [DEBUG] 渲染消息:', {
              messageId: message.id,
              content: message.content,
              senderId: message.senderId,
              index,
              isOwn,
              tempIsOwn,
              finalIsOwn,
              className: `flex ${finalIsOwn ? 'justify-end' : 'justify-start'}`
            })
            return (
            <div
              key={message.id}
              className={`flex ${finalIsOwn ? 'justify-end' : 'justify-start'}`}
            >
              <div className={`flex max-w-xs lg:max-w-md ${finalIsOwn ? 'flex-row-reverse' : 'flex-row'}`}>
                {/* 头像 */}
                {!finalIsOwn && (
                  <div className="avatar mr-2 flex-shrink-0">
                    {getAvatar(message) ? (
                      <img
                        className="avatar-image"
                        src={getAvatar(message)}
                        alt={getDisplayName(message)}
                      />
                    ) : (
                      <div className="avatar-fallback bg-gray-500 text-white">
                        {getDisplayName(message).charAt(0).toUpperCase()}
                      </div>
                    )}
                  </div>
                )}
                
                {/* 消息气泡 */}
                <div className={`message-bubble animate-slide-up max-w-[85%] sm:max-w-xs lg:max-w-md ${
                  finalIsOwn 
                    ? 'message-bubble-sent' 
                    : 'message-bubble-received'
                }`}>
                  <p className="text-sm font-medium">{message.content}</p>
                  <p className={`text-xs mt-2 ${
                    finalIsOwn 
                      ? 'text-primary-200' 
                      : 'text-secondary-500'
                  }`}>
                    {formatMessageTime(message.createdAt)}
                  </p>
                </div>
              </div>
            </div>
            )
          })
        )}
        
        {/* 正在输入指示器 */}
        {isTyping && (
          <div className="flex justify-start">
            <div className="flex max-w-xs lg:max-w-md">
              <div className="avatar mr-2 flex-shrink-0">
                <div className="avatar-fallback bg-gray-500 text-white">
                  TA
                </div>
              </div>
              <div className="message-bubble message-bubble-received">
                <div className="flex space-x-1">
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
                </div>
              </div>
            </div>
          </div>
        )}
        
        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div className="flex-shrink-0 bg-white/95 backdrop-blur-md border-t border-white/20 px-3 sm:px-4 lg:px-6 py-3 sm:py-4 shadow-soft">
        <div className="flex items-end space-x-2 sm:space-x-3">
          {/* 附件按钮 */}
          <button
            type="button"
            className="flex-shrink-0 p-2 sm:p-3 text-secondary-400 hover:text-primary-600 hover:bg-primary-50/50 rounded-xl transition-all duration-200"
          >
            <PhotoIcon className="h-4 w-4 sm:h-5 sm:w-5" />
          </button>
          
          {/* 表情按钮 */}
          <button
            type="button"
            className="flex-shrink-0 p-2 sm:p-3 text-secondary-400 hover:text-primary-600 hover:bg-primary-50/50 rounded-xl transition-all duration-200"
          >
            <FaceSmileIcon className="h-4 w-4 sm:h-5 sm:w-5" />
          </button>
          
          {/* 输入框 */}
          <div className="flex-1 min-w-0">
            <textarea
              ref={inputRef}
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="输入消息... ✍️"
              rows={1}
              className="w-full resize-none border border-secondary-200 rounded-xl px-3 sm:px-4 py-2 sm:py-3 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white/90 backdrop-blur-sm shadow-soft transition-all duration-200 text-sm sm:text-base"
              style={{ minHeight: '40px', maxHeight: '120px' }}
            />
          </div>
          
          {/* 发送按钮 */}
          <button
            type="button"
            onClick={handleSendMessage}
            disabled={!newMessage.trim()}
            className="flex-shrink-0 p-2 sm:p-3 bg-gradient-to-r from-primary-500 to-primary-600 text-white rounded-xl hover:from-primary-600 hover:to-primary-700 disabled:bg-secondary-300 disabled:cursor-not-allowed transition-all duration-200 shadow-pink hover:shadow-glow disabled:shadow-none"
          >
            <PaperAirplaneIcon className="h-4 w-4 sm:h-5 sm:w-5" />
          </button>
        </div>
      </div>
      
      {/* 调试面板 */}
      <DebugPanel />
    </div>
  )
}

export default ChatPage